$("#mfile").fileinput({
    showPreview: true,
    showUpload: true,
    elErrorContainer: '#kartik-file-errors',
    uploadUrl: '/admin/upload/file?type=CouponTpl&f=pic',
    allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
}).on("fileuploaded", function (event, data) {
    console.log(data);
    $("#hidpic").val(data.response.data);
})

function typeFormatter(value, row, index) {
    if (value == undefined || value == "") return "";
    else if (value == 1)
        return "代金券";
    else if (value == 2)
        return "满减券";
    else if (value == 3)
        return "折扣券";
    else if (value == 4)
        return "加息券";
    else if (value == 5)
        return "积分";
    else if (value == 10)
        return "次卡";
    else if (value == 11)
        return "周卡";
    else if (value == 12)
        return "月卡";
    else if (value == 13)
        return "季卡";
    else if (value == 14)
        return "半年卡";
    else if (value == 15)
        return "年卡";
    else if (value == 16)
        return "畅游卡";
    else return ""
}

function validTypeFormatter(value, row, index) {
    if (value == undefined || value == "") return "";
    else if (value == 1)
        return "领取生效";
    else if (value == 2)
        return "固定日期开始生效";
    else return ""
}

function changeState(id, state) {
    $.ajax({
        type: 'POST',
        url: "changeState",
        data: {
            id: id,
            state: state
        },
        success: function () {
            $('#mytable').bootstrapTable('refresh', {url: '/admin/coupontpl/list'});
        },
        dataType: "json"
    });
}

function changeHomeState(id, state) {
    $.ajax({
        type: 'POST',
        url: "changeHomeState",
        data: {
            id: id,
            state: state
        },
        success: function () {
            $('#mytable').bootstrapTable('refresh', {url: '/admin/coupontpl/list'});
        },
        dataType: "json"
    });
}

function deleteOne(id) {5
    swal({
        title: '您确定要删除此行数据？',
        text: '你将无法恢复它！',
        type: 'warning',
        showCancelButton: true,
        confirmButtonColor: '#3085d6',
        cancelButtonColor: '#ed5666',
        confirmButtonText: '确定删除！',
        cancelButtonText: '取消删除！',
        confirmButtonClass: 'btn btn-success',
        cancelButtonClass: 'btn btn-danger',
        buttonsStyling: false
    }).then(function () {

        $.ajax({
            type: 'POST',
            url: "deleteOne",
            data: {
                id: id,
            },
            success: function (status) {
                if (status == 1) {
                    swal({title: "删除成功", text: "", type: "success"})
                    $('#mytable').bootstrapTable('refresh', {url: '/admin/coupontpl/list'});
                } else {
                    swal({title: "删除失败", text: "", type: "error"})
                }
            },
            dataType: "json"
        });

    }, function (dismiss) {
        // dismiss的值可以是'cancel', 'overlay',
        // 'close', 'timer'
        if (dismiss === 'cancel') {
            swal({title: '您已取消操作！', text: '', timer: 2000})
        }
    })
}

function setquanGoods(id) {
    $("#tplid").val(id);
    $.ajax({
        type: 'POST',
        url: "getQuanGoods",
        data: {
            tplid: id,
        },
        success: function (e) {
            if(e.info){
                $("#gid").val(e.info.id);
                $("#gname").val(e.info.name);
                $("#characteristic").val(e.info.characteristic);
                $("#price").val(e.info.price);
                $("#saleprice").val(e.info.saleprice);

                $("#mfilephotos").fileinput('destroy');
                $("#mfilephotos").fileinput({
                    showPreview: true,
                    showUpload: true,
                    append: true,overwriteInitial:false,
                    uploadClass: "btn btn-info",
                    uploadLabel: "上传",removeLabel: "移除",language: "zh",
                    uploadIcon: "<i class=\"glyphicon glyphicon-upload\"></i> ",
                    initialPreviewShowDelete: true,
                    initialPreviewAsData: true,
                    initialPreviewFileType: 'image',
                    initialPreview: getPreviewList(e.info.photos),
                    previewFileIcon: '<i class="fa fa-file"></i>',
                    allowedPreviewTypes: ['image'],
                    initialPreviewConfig: getPreviewConfig(e.info.photos, 'Goods', "info", e.info.id),
                    elErrorContainer: '#kartik-file-errors',
                    uploadUrl: '/admin/upload/file?type=Goods&f=photos',
                    allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
                }).on("fileuploaded", function (event, data) {
                    console.log(data);
                    console.log("---------------before hidphotos.val()="+$("#hidphotos").val());
                    $("#hidphotos").val($("#hidphotos").val().length==0?data.response.data:$("#hidphotos").val()+ ";" + data.response.data);
                    console.log("---------------after hidphotos.val()="+$("#hidphotos").val());
                }).on('filedeleted', function(event, key, jqXHR, data) {
                    console.log('---------filedeleted Key = ' + key);
                    console.log($("#hidphotos").val());
                    $("#hidphotos").val(filedeleted($("#hidphotos").val(),key));
                    console.log($("#hidphotos").val());
                })
                $("#hidphotos").val(e.info.info)

                $("#mfileinfo").fileinput('destroy');
                $("#mfileinfo").fileinput({
                    showPreview: true,
                    showUpload: true,
                    append: true,overwriteInitial:false,
                    uploadClass: "btn btn-info",
                    uploadLabel: "上传",removeLabel: "移除",language: "zh",
                    uploadIcon: "<i class=\"glyphicon glyphicon-upload\"></i> ",
                    initialPreviewShowDelete: true,
                    initialPreviewAsData: true,
                    initialPreviewFileType: 'image',
                    initialPreview: getPreviewList(e.info.info),
                    previewFileIcon: '<i class="fa fa-file"></i>',
                    allowedPreviewTypes: ['image'],
                    initialPreviewConfig: getPreviewConfig(e.info.info, 'Goods', "info", e.info.id),
                    elErrorContainer: '#kartik-file-errors',
                    uploadUrl: '/admin/upload/file?type=Goods&f=info',
                    allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
                }).on("fileuploaded", function (event, data) {
                    console.log(data);
                    console.log("---------------before hidinfo.val()="+$("#hidinfo").val());
                    $("#hidinfo").val($("#hidinfo").val().length==0?data.response.data:$("#hidinfo").val()+ ";" + data.response.data);
                    console.log("---------------after hidinfo.val()="+$("#hidinfo").val());
                }).on('filedeleted', function(event, key, jqXHR, data) {
                    console.log('---------filedeleted Key = ' + key);
                    console.log($("#hidinfo").val());
                    $("#hidinfo").val(filedeleted($("#hidinfo").val(),key));
                    console.log($("#hidinfo").val());
                })
                $("#hidinfo").val(e.info.info)

            }else{
                $("#mfilephotos").fileinput('destroy');
                $("#mfilephotos").fileinput({
                    showPreview: true,
                    showUpload: true,
                    elErrorContainer: '#kartik-file-errors',
                    uploadUrl: '/admin/upload/file?type=Goods&f=photos',
                    allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
                }).on("fileuploaded", function (event, data) {
                    console.log(data);
                    $("#hidphotos").val($("#hidphotos").val().length==0? data.response.data:($("#hidphotos").val()+";"+data.response.data));
                })

                $("#mfileinfo").fileinput('destroy');
                $("#mfileinfo").fileinput({
                    showPreview: true,
                    showUpload: true,
                    elErrorContainer: '#kartik-file-errors',
                    uploadUrl: '/admin/upload/file?type=Goods&f=info',
                    allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
                }).on("fileuploaded", function (event, data) {
                    console.log(data);
                    $("#hidinfo").val($("#hidinfo").val().length==0? data.response.data:($("#hidinfo").val()+";"+data.response.data));
                })
            }
            $("#quangoods-form").modal("show");
        },
        dataType: "json"
    });


}

var editsw = [];
/**
 * 为模态框填充数据
 */
$('#modal-form').on('show.bs.modal', function (event) {
    var button = $(event.relatedTarget); // 触发事件的按钮
    var index = button.data('index');
    var modal = $(this);
    var data = $('#mytable').bootstrapTable("getData")[index]
    console.log(data)

    modal.find('#id').val(data.id)
    modal.find('#name').val(data.name)
    modal.find('#remark').val(data.remark)
    modal.find('#type').find("option[value='" + data['type'] + "']").attr("selected", true);
    editsw["isRepeat"] == undefined ? editsw["isRepeat"] = new Switchery(document.querySelector('#isRepeat'), {color: "#1AB394"}) : ""
    if (data.isRepeat == 1) {
        setSwitchery(editsw["isRepeat"], true);
    } else {
        setSwitchery(editsw["isRepeat"], false);
    }
    modal.find('#repeatNum').val(data.repeatNum)
    modal.find('#total').val(data.total)
    modal.find('#expire').val(data.expire)
    modal.find('#use').val(data.use)
    modal.find('#discount').val(data.discount)

    modal.find('#validType').find("option[value='" + data['validType'] + "']").attr("selected", true);
    modal.find('#allcategory').find("option[value='" + data['allcategory'] + "']").attr("selected", true);
    modal.find('#isForever').find("option[value='" + data['isForever'] + "']").attr("selected", true);
    modal.find('#starttime').val(data.starttime)
    modal.find('#endtime').val(data.endtime)
    modal.find('#cost').val(data.cost)
    modal.find('#cunit').val(data.cunit)
    modal.find('#usemin').val(data.usemin)
    modal.find('#maxvalue').val(data.maxvalue)
    modal.find('#categories').val(data.categories)
    modal.find('#gids').val(data.gids)
    if ($("#isAdmin").val() == 1) {
        editsw["isSystem"] == undefined ? editsw["isSystem"] = new Switchery(document.querySelector('#isSystem'), {color: "#1AB394"}) : ""
        if (data.isSystem == 1) {
            setSwitchery(editsw["isSystem"], true);
        } else {
            setSwitchery(editsw["isSystem"], false);
        }
    }

    if (data.type == 2) {
        $("#useminDiv2").show()
    } else {
        $("#useminDiv2").hide()
    }
    if (data.isRepeat == 1) {
        $("#repeatNumDiv2").show()
    } else {
        $("#repeatNumDiv2").hide()
    }

    if (data.allcategory == 1) {
        $("#rowallcategory2").hide()
    } else {
        $("#rowallcategory2").show()
    }

    if (data.isForever == 1) {
        $("#validTypeDiv2").hide()
        $("#rowexeire2").hide()
        $("#rowtime2").hide()
    } else {
        $("#validTypeDiv2").show()
        if (data.validType == 1) {
            $("#rowexpire2").show()
            $("#rowtime2").hide()
        } else {
            $("#rowexpire2").hide()
            $("#rowtime2").show()
        }
    }

    $("#mfilepic").fileinput('destroy');
    $("#mfilepic").fileinput({
        showPreview: true,
        showUpload: true,
        append: true,
        overwriteInitial:false,
        uploadClass: "btn btn-info",
        uploadLabel: "上传",
        removeLabel: "移除",
        language: "zh",
        maxFileCount: 1,
        uploadIcon: "<i class=\"glyphicon glyphicon-upload\"></i> ",
        initialPreviewShowDelete: true,
        initialPreviewAsData: true,
        initialPreviewFileType: 'image',
        initialPreview: getPreviewList(data.pic),
        previewFileIcon: '<i class="fa fa-file"></i>',
        allowedPreviewTypes: ['image'],
        initialPreviewConfig: getPreviewConfig(data.pic, 'CouponTpl', "pic", data.id),
        elErrorContainer: '#kartik-file-errors',
        uploadUrl: '/admin/upload/file?type=CouponTpl&f=pic',
        allowedFileExtensions: ["jpg", "jpeg", "png", "gif"]
    }).on("fileuploaded", function (event, data) {
        console.log(data);
        $("#hidpic2").val(data.response.data);
    }).on('filedeleted', function (event, key, jqXHR, data) {
        console.log('Key = ' + key);
        $("#hidpic2").val('');
    })
    $("#hidpic2").val(data.pic)

    typeChange(data.type,"modify")
})

function quanFormatter(value, row, index) {
    var state = row.state;
    var isHome = row.isHome;
    var sid = row.sid;
    var id = row.id;
    var res = '<button data-toggle="modal" class="btn-sm btn-primary" href="list.html#modal-form" data-row=' + id + ' data-index=' + index + '>修改</button>';
    if (state == undefined) {
    } else if (state == 1)
        res += ' <button type="button" class="btn-sm btn-info" onclick="changeState(\'' + id + '\',-1)" >禁用</button>';
    else
        res += ' <button typ-e="button" class="btn-sm btn-info" onclick="changeState(\'' + id + '\',1)" >启用</button>';

    if (isHome == undefined) {
    } else if (isHome == 1&&(sid==undefined||sid==""||sid==0))
        res += ' <button type="button" class="btn-sm btn-info" onclick="changeHomeState(\'' + id + '\',-1)" >禁用首页券</button>';
    else if(isHome != 1&&(sid==undefined||sid==""||sid==0))
        res += ' <button typ-e="button" class="btn-sm btn-info" onclick="changeHomeState(\'' + id + '\',1)" >启用首页券</button>';
    res += ' <button typ-e="button" class="btn-sm btn-danger" onclick="setquanGoods(\'' + id + '\')">设置券类商品</button>';
    res += ' <button typ-e="button" class="btn-sm btn-danger" onclick="deleteOne(\'' + id + '\')">删除</button>';
    return res;
}

function kucunformatter(value, row, index) {
    return value==-1?"无限制":value;
}

//tableHeight函数
function tableHeight() {
    //可以根据自己页面情况进行调整
    return $(window).height() - 200;
}

function isForeverChange(val) {
    if (val != 1) {
        $("#validTypeDiv").show()
        $("#validTypeDiv2").show()
        $("#rowexpire").show()
        $("#rowexpire2").show()
    } else {
        $("#validTypeDiv").hide()
        $("#validTypeDiv2").hide()
        $("#rowexpire").hide()
        $("#rowexpire2").hide()
        $("#rowtime").hide()
        $("#rowtime2").hide()
    }
}

function typeChange(val,act) {
    console.log('---------val='+val)
    if (val == 2) {
        $("#useminDiv").show()
        $("#useminDiv2").show()
    } else {
        $("#usemin").val("")
        $("#usemin2").val("")
        $("#useminDiv").hide()
        $("#useminDiv2").hide()
    }

    if(val>=10){
        $("#mfile"+act).show()
        $(".ncika").hide()
    }else{
        $("#mfile"+act).hide()
        $(".ncika").show()
    }
    if(val==10)$(".eq10").show()
    else $(".eq10").hide()

    if(val<=10)$(".less10").show()
    else $(".less10").hide()

}

function validTypeChange(val) {
    if (val == 1) {
        $("#rowexpire").show()
        $("#rowexpire2").show()
        $("#rowtime").hide()
        $("#rowtime2").hide()
    } else {
        $("#rowexpire").hide()
        $("#rowexpire2").hide()
        $("#rowtime").show()
        $("#rowtime2").show()
    }
}

function isRepeatChange(val) {
    if (val != 1) {
        $("#repeatNumDiv").hide()
        $("#repeatNumDiv2").hide()
    } else {
        $("#repeatNumDiv").show()
        $("#repeatNumDiv2").show()
    }
}

function allcategoryChange(val) {
    if (val == 0) {
        $("#rowallcategory").hide()
        $("#rowallcategory2").hide()
    } else {
        $("#rowallcategory").show()
        $("#rowallcategory2").show()
    }
}

$(function () {

    $('#starttime').datepicker(dateformat);
    $('#starttime2').datepicker(dateformat);

    $('#endtime').datepicker(dateformat);
    $('#endtime2').datepicker(dateformat);

    var sw = [];
    $(".js-switch").each(function (i, e) {
        sw[i] = new Switchery(e, {color: "#1AB394"})
    })
    $(window).resize(function () {
        $('#mytable').bootstrapTable('resetView', {
            height: tableHeight()
        })
    })
    //生成用户数据
    $('#mytable').bootstrapTable({
        method: 'get',
        url: "/admin/coupontpl/list",
        // height:520,//高度调整
        // toolbar: '#toolbar',
        striped: true, //是否显示行间隔色
        dataField: "records",
        pagination: true,//是否分页
        queryParamsType: 'limit',
        queryParams: queryParams,
        sidePagination: 'server',
        pageNumber: 1, //初始化加载第一页，默认第一页
        pageSize: 50,//单页记录数
        pageList: [50, 100, 200, 500],//分页步进值
        showExport: true,//显示导出
        showRefresh: false,//刷新按钮
        showColumns: false,
        clikToSelect: true,//是否启用点击选中行
        // toolbarAlign:'right',
        // buttonsAlign:'right',//按钮对齐方式
        columns: [
            {
                title: '全选',
                field: 'select',
                checkbox: true,
                width: 25,
                align: 'center',
                valign: 'middle'
            },
            {
                title: 'ID',
                field: 'id',
                visible: false
            },
            {
                title: '优惠券模板名称',
                field: 'name'
            },
            {
                title: '优惠券类型',
                field: 'type',
                formatter: "typeFormatter"
            },
            {
                title: '能否重复领用',
                field: 'isRepeat',
                formatter: "sfFormatter"
            },
            // {
            //     title: '可重复领取张数',
            //     field: 'repeatNum'
            // },
            {
                title: '库存',
                formatter: "kucunformatter",
                field: 'total'
            },
            // {
            //     title: '总价值',
            //     field: 'discount'
            // },
            {
                title: '是否长期有效',
                field: 'isForever',
                formatter: "sfFormatter"
            },
            // {
            //     title: '生效方式',
            //     field: 'validType',
            //     formatter: "validTypeFormatter"
            // },
            {
                title: '所属门店',
                field: 'sname'
            },
            {
                title: '是否首页券',
                field: 'isHome',
                formatter: "sfFormatter"
            },
            {
                title: '启用状态',
                field: 'state',
                formatter: "stateFormatter"
            },
            {
                title: '操作',
                field: 'Attribute',
                align: 'center',
                width: 170,
                formatter: quanFormatter
            }
        ],
        locale: 'zh-CN',//中文支持,
    })

    //请求服务数据时所传参数
    function queryParams(params) {
        var p = {
            limit: params.limit,
            offset: params.offset,
            sort: params.sort,
            order: params.order
            , search: $('#search').val()
            , status: $('#qstatus').val()
        }
        return p;
    }

    $('#search_btn').click(function () {
        var p = {
            status: $('#qstatus').val(),
            search: $('#search').val(),
            ts: new Date().getTime()
        };
        $('#mytable').bootstrapTable('refresh', p);
    })

    /*
     * 验证错误提示信息高亮
     */
    $.validator.setDefaults({
        highlight: function (e) {
            $(e).closest(".form-group").removeClass("has-success").addClass("has-error")
        }, success: function (e) {
            e.closest(".form-group").removeClass("has-error").addClass("has-success")
        }, errorElement: "span", errorPlacement: function (e, r) {
            e.appendTo(r.is(":radio") || r.is(":checkbox") ? r.parent().parent().parent() : r.parent())
        }, errorClass: "help-block m-b-none", validClass: "help-block m-b-none"
    }), $("#aform").validate(), $("#mform").validate();
})

function checkAdd() {
    $('input:checkbox').each(function (index, item) {
        if ($(this).prop("checked")) {
            $(this).val(1);
            console.log($(this).attr("name") + "=" + $(this).val())
        } else {
            $(this).val(-1);
            console.log($(this).attr("name") + "=" + $(this).val())
        }
    });

    if( $("#type2").val()==''){
        swal({title: "信息提示", text: "请选择优惠券类型", type: "error"})
        return false
    }

    // $('input').each(function (index, item) {
    //     if ($(this).attr("name")=="total"&&$(this).val()*1<=0){
    //         swal({title: '库存不能为空且必须大于0', text: '', timer: 2000})
    //         return false
    //     }
    // });

    return true;
}

function checkAddquan() {
    $('input:checkbox').each(function (index, item) {
        if ($(this).prop("checked")) {
            $(this).val(1);
            console.log($(this).attr("name") + "=" + $(this).val())
        } else {
            $(this).val(-1);
            console.log($(this).attr("name") + "=" + $(this).val())
        }
    });
    if( $("#gname").val()==''){
        swal({title: "信息提示", text: "商品名称不能为空", type: "success"})
        return false
    }
    if( $("#price").val()==''){
        swal({title: "信息提示", text: "商品原价不能为空", type: "success"})
        return false
    }
    if( $("#saleprice").val()==''){
        swal({title: "信息提示", text: "实际售价不能为空", type: "success"})
        return false
    }
    if( $("#hidphotos").val()==''){
        swal({title: "信息提示", text: "商品轮播图不能为空", type: "success"})
        return false
    }
    if( $("#hidinfo").val()==''){
        swal({title: "信息提示", text: "商品详情不能为空", type: "success"})
        return false
    }
    return true;
}

function checkModify() {
    $('input:checkbox').each(function (index, item) {
        if ($(this).prop("checked")) {
            $(this).val(1);
            console.log($(this).attr("id") + "=" + $(this).val())
        } else {
            $(this).val(-1);
            console.log($(this).attr("id") + "=" + $(this).val())
        }
    });

    if( $("#type").val()==''){
        swal({title: "信息提示", text: "请选择优惠券类型", type: "error"})
        return false
    }
    // if ($("#total").val()*1<=0){
    //     swal({title: '库存不能为空且必须大于0', text: '', timer: 2000})
    //     return false
    // }
    return true;
}